package net.ncraft.mc.easyframework.async.core;

import net.ncraft.mc.easyframework.aop.anno.Aspect;
import net.ncraft.mc.easyframework.aop.anno.Pointcut;
import net.ncraft.mc.easyframework.aop.core.JoinPoint;
import net.ncraft.mc.easyframework.async.anno.Async;
import net.ncraft.mc.easyframework.context.anno.Autowired;
import net.ncraft.mc.easyframework.context.anno.Component;

import java.util.concurrent.ThreadPoolExecutor;

@Aspect
@Component
public class AsyncAspect {


    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Pointcut(Async.class)
    public void async(JoinPoint joinPoint) {
        if (threadPoolExecutor != null) {
            threadPoolExecutor.submit(() -> {
                try {
                    joinPoint.proceed();
                } catch (Throwable e) {
                    throw new RuntimeException(e);
                }
            });
        } else {
            new Thread(() -> {
                try {
                    joinPoint.proceed();
                } catch (Throwable e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
    }

}
